package cn.zn.oss.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.zn.base.exception.CustomException;
import cn.zn.base.properties.ZnAdminProperties;
import cn.zn.oss.dto.FileDto;
import cn.zn.oss.service.FileService;
import cn.zn.oss.utils.FileUploadUtil;
import cn.zn.oss.utils.MimeTypeUtil;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@Service
public class FileServiceImpl implements FileService {

    @Override
    public FileDto uploadFile(MultipartFile file, HttpServletRequest request) throws Exception {
        FileDto fileDto = new FileDto();

        // 上传文件路径
        String filePath = ZnAdminProperties.getUploadPath();
        // 上传并返回新文件名称
        String fileName = FileUploadUtil.upload(filePath, file);
        fileDto.setFileName(file.getOriginalFilename());
        fileDto.setUrl(fileName);
        return fileDto;
    }

    @Override
    public void downloadFile(String fileName, String filePath, HttpServletResponse response) throws Exception {
        if (!checkAllowDownload(filePath)) {
            throw new CustomException(StrUtil.format("文件名称({})非法，不允许下载。 ", fileName));
        }
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        setAttachmentResponseHeader(response, fileName);
        FileUtil.writeToStream(ZnAdminProperties.getProfile() + filePath, response.getOutputStream());
    }

    public static String getDomain(HttpServletRequest request) {
        StringBuffer url = request.getRequestURL();
        String contextPath = request.getServletContext().getContextPath();
        return url.delete(url.length() - request.getRequestURI().length(), url.length()).append(contextPath).toString();
    }

    /**
     * 检查文件是否可下载
     *
     * @param resource 需要下载的文件
     * @return true 正常 false 非法
     */
    private boolean checkAllowDownload(String resource) {
        // 禁止目录上跳级别
        if (StrUtil.contains(resource, "..")) {
            return false;
        }

        String extName = FileNameUtil.extName(resource);
        if (StrUtil.isNotBlank(extName)) {
            extName = extName.toLowerCase();
        }
        // 检查允许下载的文件规则
        if (ArrayUtil.contains(MimeTypeUtil.DEFAULT_ALLOWED_EXTENSION, extName)) {
            return true;
        }

        // 不在允许下载的文件规则
        return false;
    }

    /**
     * 下载文件名重新编码
     *
     * @param response     响应对象
     * @param realFileName 真实文件名
     * @return
     */
    private void setAttachmentResponseHeader(HttpServletResponse response, String realFileName) throws UnsupportedEncodingException {
        String percentEncodedFileName = percentEncode(realFileName);

        StringBuilder contentDispositionValue = new StringBuilder();
        contentDispositionValue.append("attachment; filename=")
                .append(percentEncodedFileName)
                .append(";")
                .append("filename*=")
                .append("utf-8''")
                .append(percentEncodedFileName);

        response.setHeader("Content-disposition", contentDispositionValue.toString());
    }

    /**
     * 百分号编码工具方法
     *
     * @param s 需要百分号编码的字符串
     * @return 百分号编码后的字符串
     */
    private String percentEncode(String s) throws UnsupportedEncodingException {
        String encode = URLEncoder.encode(s, StandardCharsets.UTF_8.toString());
        return encode.replaceAll("\\+", "%20");
    }

}
